package com.greate.community.controller.Background;

import com.alibaba.fastjson.JSON;
import com.greate.community.common.Result;
import com.greate.community.entity.BackgroundLoginEntity;
import com.greate.community.entity.User;
import com.greate.community.service.UserService;
import com.greate.community.util.HostHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static org.springframework.web.bind.annotation.RequestMethod.POST;

@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "http://localhost:5666")
public class BackgroundLoginController {

    private static final Logger logger = LoggerFactory.getLogger(BackgroundLoginController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    // 后台用户登录接口
    @RequestMapping(value = "/login", method = POST)
    public Result<Object> login(@RequestBody BackgroundLoginEntity backgroundLoginEntity) {
        // 固定accessToken
        Boolean captcha = backgroundLoginEntity.getCaptcha();
        String password = backgroundLoginEntity.getPassword();
        String selectAccount = backgroundLoginEntity.getSelectAccount();
        String username = backgroundLoginEntity.getUsername();


        if (!"vben".equals(username)) {
            return Result.error("用户名错误");
        }
        if (!"123456".equals(password)) {
            return Result.error("密码错误");
        }
        if (Objects.equals(selectAccount,"vben")) {
            // 创建一个包含所需数据的Map或对象
            Map<String, Object> userData = new HashMap<>();
            userData.put("id", 0);
            userData.put("password", "123456");
            userData.put("realName", "Vben");
            userData.put("roles", Collections.singletonList("super"));
            userData.put("username", "vben");
            userData.put("accessToken", "hnczjr");

            return Result.success(userData);
        }
        if (captcha == false) {
            return Result.error("验证码错误");
        }

        // 如果走到这里，也返回相同的用户数据
        User user = userService.findUserByName("vben");

        Map<String, Object> userData = new HashMap<>();
        userData.put("id", 0);
        userData.put("password", "123456");
        userData.put("realName", "Vben");
        userData.put("roles", Collections.singletonList("super"));
        userData.put("username", "vben");
        userData.put("accessToken", user.getAccessToken());

        return Result.success(userData);
    }

/*
    // 用户管理
    @GetMapping("/user/manage")
    public String userManage() {
        return "/site/admin/user_manage";
    }

    // 获取单个用户信息
    @GetMapping("/user/{id}")
    @ResponseBody
    public Result<User> getUser(@PathVariable("id") int id) {
        try {
            User user = userService.findUserById(id);
            if (user != null) {
                return Result.success(user);
            }
            return Result.error("用户不存在");
        } catch (Exception e) {
            logger.error("获取用户信息失败", e);
            return Result.error("获取用户信息失败: " + e.getMessage());
        }
    }

    // 搜索用户
    @GetMapping("/user/search")
    @ResponseBody
    public Result<List<User>> searchUsers(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Integer type,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int limit) {

        try {
            List<User> users = userService.searchUsers(keyword, status, type, page, limit);
            int total = userService.getUserCount(keyword, status, type);

            return Result.build(0, "success", users);
        } catch (Exception e) {
            logger.error("搜索用户失败", e);
            return Result.error("搜索失败: " + e.getMessage());
        }
    }

    // 添加用户
    @PostMapping("/user/add")
    @ResponseBody
    public Result<Void> addUser(@RequestBody User user) {
        try {
            // 设置默认头像
            user.setHeaderUrl("http://static.nowcoder.com/images/head/notify.png");
            // 设置默认密码
            user.setPassword("123456");
            // 设置默认状态
            user.setStatus(1);

            userService.addUser(user);
            return Result.success();
        } catch (Exception e) {
            logger.error("添加用户失败", e);
            return Result.error("添加失败: " + e.getMessage());
        }
    }

    // 更新用户
    @PostMapping("/user/update")
    @ResponseBody
    public Result<Void> updateUser(@RequestBody User user) {
        try {
            // 获取原用户信息
            User oldUser = userService.findUserById(user.getId());
            if (oldUser == null) {
                return Result.error("用户不存在");
            }
            // 保留原密码
            user.setPassword(oldUser.getPassword());
            // 保留原头像
            user.setHeaderUrl(oldUser.getHeaderUrl());
            userService.updateUser(user);
            return Result.success();
        } catch (Exception e) {
            logger.error("更新用户失败", e);
            return Result.error("更新失败: " + e.getMessage());
        }
    }

    // 删除用户
    @PostMapping("/user/delete/{id}")
    @ResponseBody
    public Result<Void> deleteUser(@PathVariable("id") int id) {
        try {
            userService.deleteUser(id);
            return Result.success();
        } catch (Exception e) {
            logger.error("删除用户失败", e);
            return Result.error("删除失败: " + e.getMessage());
        }
    }

    // 更新用户状态
    @PostMapping("/user/status/{id}")
    @ResponseBody
    public Result<Void> updateUserStatus(
            @PathVariable("id") int id,
            @RequestParam int status) {
        try {
            userService.updateUserStatus(id, status);
            return Result.success();
        } catch (Exception e) {
            logger.error("更新用户状态失败", e);
            return Result.error("状态更新失败: " + e.getMessage());
        }
    }*/
} 